import 'package:flutter/material.dart';
import 'package:flutter_web_view/util/toast_util.dart';
import 'package:images_picker/images_picker.dart';
import 'package:scan/scan.dart';

/// 二维码扫描页面
class ScanPage extends StatefulWidget {
  const ScanPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return ScanPageState();
  }
}

class ScanPageState extends State<ScanPage> {
  IconData _lightIcon = Icons.flash_on;
  final ScanController _controller = ScanController();

  /// 返回扫描结果
  Future<void> _onScanResult(String? result, BuildContext context) async {
    result = result ?? "";
    if (!context.mounted) {
      return;
    }
    final navigator = Navigator.of(context);
    if (result.isEmpty) {
      ToastUtil.toast("扫描内容非网址Url");
    }
    navigator.pop(result);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
          title: const Text("二维码扫描")),
      body: Stack(children: [
        ScanView(
          controller: _controller,
          scanLineColor: Colors.blue,
          onCapture: (data) async {
            _controller.pause();
            _onScanResult(data, context);
          },
        ),
        Positioned(
          left: 50,
          bottom: 50,
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return MaterialButton(
                  child: Icon(
                    _lightIcon,
                    size: 40,
                    color: Colors.blue,
                  ),
                  onPressed: () {
                    _controller.toggleTorchMode();
                    if (_lightIcon == Icons.flash_on) {
                      _lightIcon = Icons.flash_off;
                    } else {
                      _lightIcon = Icons.flash_on;
                    }
                    setState(() {});
                  });
            },
          ),
        ),
        Positioned(
          right: 50,
          bottom: 50,
          child: MaterialButton(
              child: const Icon(
                Icons.image,
                size: 40,
                color: Colors.blue,
              ),
              onPressed: () async {
                List<Media>? res =
                    await ImagesPicker.pick(count: 1, maxSize: 1024);
                if (res != null) {
                  _controller.pause();
                  Media image = res.first;
                  String? result = await Scan.parse(image.path);
                  _onScanResult(result, context);
                }
              }),
        ),
      ]),
    );
  }
}
